package com.bytecollege.controller;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bytecollege.model.User;
import com.bytecollege.service.Impl.*;
import com.bytecollege.util.R;
import com.bytecollege.util.ValidateCodeUtils;
import com.bytecollege.vo.*;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @ClassName: UserController
 * @Description: 实现用户的操作
 * @Author: Sun
 * @Date: 2022/10/20 8:57
 */
@Controller
@RequestMapping("/user")
@Log
public class UserController {

    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private CremarkServiceImpl cremarkService;
    @Autowired
    AremarkServiceImpl aremarkService;
    @Autowired
    FootmarkServiceImpl footmarkService;

    @Autowired
    private ArticleServiceImpl articleService;
    @Autowired
    private ArticleCollectServiceImpl articleCollectService;

    @Autowired
    private CourseCollectServiceImpl courseCollectService;

    @GetMapping("/tologin")
    public String toLogin() {
        return "login";
    }

    /**
     * 发送验证码邮箱
     * @param user
     */
    @PostMapping("/sendMsg")
    @ResponseBody
    public R sendMsg(UserVo user,HttpSession session) {
// 获取邮箱账号
        String email = user.getUserEmail();
        log.info(email);

        String subject = "Byte云课登录验证码";

        if (StringUtils.isNotEmpty(email)) {
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            String context = "欢迎使用Byte云课，登录验证码为: " + code + ",3分钟内有效，请妥善保管!";
            log.info(code);
            // 真正地发送邮箱验证码
            userService.sendMsg(email, subject, context);
            //

            session.setAttribute("code",code);
        }
        return R.builder().state(200).message("valid code send").build();
    }

    /**
     * 去登录
     *
     * @param userEmail
     * @param userPwd
     * @param session
     * @return
     */
    @PostMapping("/login")
    public String login(String userEmail, String userPwd,String code ,HttpSession session,Model model) {

        User data = userService.login(userEmail);
        String co = (String) session.getAttribute("code");
        String s = SecureUtil.md5(userPwd);
        if (data.getUserIsdelete()==1){
            model.addAttribute("msg","用户已被注销！");
            return "login";
        } else if (!data.getUserPwd().equals(s)){
            model.addAttribute("msg","密码不匹配");
            return "login";
        }else if(!co.equals(code)){
            model.addAttribute("msg","验证码不匹配");
            return "login";
        }
        session.setAttribute("data", data);
        return "redirect:/index";
    }

    /**
     * 去注册界面
     *
     * @return
     */
    @GetMapping("/toReg")
    public String toReg() {
        return "register";
    }

    /**
     * 用户注册
     *
     * @param
     * @return
     */
    @PostMapping("/reg")
    public String reg(UserVo userVo ,Model model) {
        User user = new User();
        user.setUserId(userVo.getUserId());
        user.setUserName(userVo.getUserName());
        user.setUserPwd(userVo.getUserPwd());
        user.setUserPhone(userVo.getUserPhone());
        user.setUserEmail(userVo.getUserEmail());
        int reg = userService.reg(user);
        if (reg!=0){
            model.addAttribute("msg","注册成功");
        }
        return "login";
    }

    /**
     * 去修改密码页
     *
     * @return
     */

    @GetMapping("/toUpdatePwd")
    public String toUpdatePwd() {
        return "user/toUpdatePwd";
    }

    /**
     * 修该密码
     *
     * @param userId
     * @param userPwd
     * @param newPwd
     * @param model
     * @return
     */
    @PostMapping("UpdatePwd")
    public String updatePwd(Integer userId, String userPwd, String newPwd, Model model) {
        boolean b = userService.updatePassword(userId, userPwd, newPwd);
        if (b) {
            model.addAttribute("msg", "密码修改成功！");
        } else {
            model.addAttribute("msg", "密码修改失败");
        }
        return "redirect:/user/tologin";
    }

    /**
     * 去修改用户信息
     *
     * @return
     */

    @GetMapping("/toUpdateInfo")
    public String toUpdateInfo() {
        return "user/updateInfo";
    }

    /**
     * 修改用户信息
     *
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/updateInfo")
    public String UpdateInfo(User user, HttpSession session) {
        userService.updateInfo(user);

        User data = userService.getById(user.getUserId());
        session.setAttribute("data", data);
        return "user/updateInfo";
    }

    /**
     * 用户退出
     *
     * @param request
     * @param model
     * @return
     */
    @GetMapping("/logout")
    public String logout(HttpServletRequest request, Model model) {
        HttpSession session = request.getSession();
        session.invalidate();
        model.addAttribute("msg", "谢谢使用！");
        return "redirect:/user/tologin";
    }

    /**
     * 获取用户评论的信息
     *
     * @param session
     * @param model
     * @return
     */

    @GetMapping("/toCreMark")
    public String toCreMark(@RequestParam (value = "pageIndex",defaultValue = "1")Integer pageIndex,HttpSession session, Model model) {
       Integer pageSize =10;
        User data = (User) session.getAttribute("data");
        Integer userId = data.getUserId();
        Page<MyCremarkVO> page = new Page<>();
       page.setRecords(cremarkService.getCremarkById(new Page<>(pageIndex,pageSize),userId));
        model.addAttribute("page", page);
        return "user/CreMarkList";
    }

    /**
     * 删除用户信息
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("delCreMark")
    public String delCreMark(Integer id, Model model) {
        int i = cremarkService.delCremarkById(id);
        if (i != 0) {
            model.addAttribute("msg", "删除成功！");
        }
        return "redirect:/user/toCreMark";
    }

    /**
     * 文章评论
     * @param pageIndex
     * @param session
     * @param model
     * @return
     */

    @GetMapping("/toAreMark")
    public String toAreMark(@RequestParam(value ="pageIndex",defaultValue = "1") Integer pageIndex ,HttpSession session, Model model) {
        Integer pageSize = 10;
        User data = (User) session.getAttribute("data");
        Integer userId = data.getUserId();
        Page<MyAreMarkVO> page = new Page<>();
        page.setRecords( aremarkService.getAllAremark(new Page<>(pageIndex,pageSize),userId));
        model.addAttribute("page", page);
        return "user/AreMarkList";
    }

    /**
     * 删除用户信息
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("delAreMark")
    public String delAreMark(Integer id, Model model) {
        int i = aremarkService.delAremarkById(id);
        if (i != 0) {
            model.addAttribute("msg", "删除成功！");
        }
        return "redirect:/user/toAreMark";
    }

    /**
     * 分页查询
     *
     * @param pageIndex
     * @param session
     * @param model
     * @return
     */
    @GetMapping("/getFootMark")
    public String getFootMark(@RequestParam(value = "pageIndex", defaultValue = "1") Integer pageIndex, HttpSession session, Model model) {
        Integer pageSize = 10;
        User data = (User) session.getAttribute("data");
        Integer userId = data.getUserId();
        Page<FootMarkVo> page = new Page<>();
        page.setRecords(footmarkService.getAllFootMark(new Page<>(pageIndex, pageSize), userId));
        model.addAttribute("page", page);
        return "user/FootMarkList";
    }

    @GetMapping("/delFootMark")
    public String delFootMark(Integer id, Model model) {
        int i = footmarkService.delFootMark(id);
        if (i != 0) {
            model.addAttribute("msg", "删除成功");
        }
        return "redirect:/user/getFootMark";
    }

    /**
     * 我的文章
     * @param pageIndex
     * @param session
     * @param model
     * @return
     */

    @GetMapping("/getArticle")
    public String getArticle(@RequestParam(value = "pageIndex", defaultValue = "1") Integer pageIndex, HttpSession session, Model model) {
        Integer pageSize = 10;
        User data = (User) session.getAttribute("data");
        Integer userId = data.getUserId();
        Page<ArticleVo> page = new Page<>();
        page.setRecords(articleService.getAllArticle(new Page<>(pageIndex, pageSize), userId));
        model.addAttribute("page", page);
        return "user/ArticleList";
    }

    /**8
     * 删除文章
     * @param id id
     * @param model
     * @return
     */
    @GetMapping("/delArticle")
    public String delArticle(Integer id, Model model) {
        int i = articleService.delArticle(id);
        if (i != 0) {
            model.addAttribute("msg", "删除成功");
        }
        return "redirect:/user/getArticle";
    }

    /**
     * 去文章详情
     * @param id
     * @param model
     * @return
     */

    @GetMapping("/toArticleCount")
    public  String   toArticleCount(Integer id, Model model){
        ArticleDetailVo article = articleService.getArticleById(id);
        model.addAttribute("article",article);
        return "user/ArticleContent";
    }

    /**
     * 获取文章收藏
     * @param pageIndex
     * @param session
     * @param model
     * @return
     */

    @GetMapping("/getArticleCollect")
    public String getArticleCollect(@RequestParam(value = "pageIndex", defaultValue = "1") Integer pageIndex, HttpSession session, Model model) {
        Integer pageSize = 10;
        User data = (User) session.getAttribute("data");
        Integer userId = data.getUserId();
        Page<ArticleCollectVo> page = new Page<>();
        page.setRecords(articleCollectService.getArticleCollect(new Page<>(pageIndex, pageSize), userId));
        model.addAttribute("page", page);
        return "user/ArticleCollectList";
    }

    /**
     * 删除
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/delArticleCollectById")
    public String delArticeCollectById(Integer id, Model model) {
        int i = articleCollectService.delArticeCollectById(id);
        if (i != 0) {
            model.addAttribute("msg", "删除成功");
        }
        return "redirect:/user/getArticleCollect";
    }


    /**
     * 课程收藏
     * @param pageIndex
     * @param session
     * @param model
     * @return
     */

    @GetMapping("/getCourseCollect")
    public String getCourseCollect(@RequestParam(value = "pageIndex", defaultValue = "1") Integer pageIndex, HttpSession session, Model model) {
        Integer pageSize = 10;
        User data = (User) session.getAttribute("data");
        Integer userId = data.getUserId();
        Page<CourseCollectVo> page = new Page<>();
        page.setRecords(courseCollectService.getCourseCollect(new Page<>(pageIndex, pageSize), userId));
        model.addAttribute("page", page);
        return "user/CourseCollectList";
    }

    /**
     * 删除课程收藏
     * @param id
     * @param model
     * @return
     */

    @GetMapping("/delCourseCollectById")
    public String delCourseCollectById(Integer id, Model model) {
        int i = courseCollectService.delCourseCollectById(id);
        if (i != 0) {
            model.addAttribute("msg", "删除成功");
        }
        return "redirect:/user/getCourseCollect";
    }

}
